#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: search.py
@contact: zwb15083976291@163.com
@time: 2022/02/28
"""
import json

from django.conf import settings
from django.db.models import Q

from common.models import BlogArticle
from common.serializers.serializer import SearchArticlesSerializer
from common.utils import add_article_search_cached_data
from utils.redis_clients import RedisClient
from utils.responses import CommonAPIResponseStatus, CommonResponse
from utils.serializers.serializer import SearchSerializer
from utils.views.views import BaseGenericAPIView


class SearchArticleView(BaseGenericAPIView):
    diff_methods_request_params = dict(get=dict(required=['search']))
    diff_methods_serializer_class = dict(get=SearchSerializer)

    def get(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        # 缓存数据到redis中
        search = self.serializer.validated_data.get('search')
        cache_ret, search_data = self.query_cache_data()
        if not cache_ret:
            add_article_search_cached_data()
            cache_ret, search_data = self.query_cache_data()
        return CommonResponse(data=self.retrieve_data(search, search_data))

    def retrieve_data(self, search, search_data: dict):
        result = []
        for key, value in search_data.items():
            key = key.decode("utf-8")
            if key.find(search) != -1:
                result.append(json.loads(value.decode("utf-8")))
        return result

    def query_cache_data(self):
        # 不存在数据
        redis_client = RedisClient()
        if not redis_client.exists(getattr(settings, "SEARCH_ARTICLES_KEY")):
            return False, []
        else:
            data = redis_client.hgetall(getattr(settings, "SEARCH_ARTICLES_KEY"))
            return True, data
